//app.js
var util = require('utils/util.js')
App({
  onLaunch: function () {
    //检查微信版本
    // this.setBanben()
    this.getHeader()
    this.getUserInfo()
  },
  onHide: function () {
  },
  unction (res) {
    wx.showModal({
      title: '出错啦',
      content: res,
    })
  },
  getHeader: function (cb) {
    //判断storage里面是否有PHPSESSID
    //如果存在则放在请求的头部
    var session_id = wx.getStorageSync('PHPSESSID');//本地取存储的sessionID  
    var that = this
    var header = that.globalData.header
    //如果不存在则发起一起请求，带回PHPSESSID并存入storage
    if (session_id == "" || session_id == null) {
      var util = require('utils/util.js')
      var getSessionId = util.wxPromisify(wx.request)

      getSessionId({
        url: that.globalData.requestip + '&c=login&a=getSessionId',
      }).then(function (res) {
        wx.setStorageSync('PHPSESSID', res.data.session_id) //如果本地没有就说明第一次请求 把返回的session id 存入本地
        header.Cookie = "PHPSESSID=" + res.data.session_id
        that.globalData.header = header
        typeof cd == 'function' && cb(that.globalData.header)
      }).catch(function (res) {
        console.log('PHPSESSID操作失败')
      })
    } else {
      header.Cookie = "PHPSESSID=" + session_id
      that.globalData.header = header
      typeof cd == 'function' && cb(that.globalData.header)
    }
  },

  //检查用户是否登陆
  checkUserIsLogin:function (cb) {
    this.getUserInfo(function(cb){
      if (cb) {
        typeof cb == "function" && cb(false)
      } else {
        wx.showModal({
          title: '登陆',
          content: '您还未登陆，请先登陆',
          showCancel: true,
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '../login/login',
              })
            }
          },
          fail: function (res) { },
          complete: function (res) { },
        })
      }
    })
  },

  //获取用户信息
  getUserInfo: function (cb) {
    var that = this
    if (that.globalData.userInfo) {
      console.log('globalData用户信息存在:登录成功')
      typeof cb == "function" && cb(that.globalData.userInfo)
    } else {
      //检查session3rd是否存在，存在则表示该用户为登录状态，不存在则需要重新登录
      var session3rd = wx.getStorageSync('SESSION3RD');//本地取存储的SESSION3RD

      var header = that.globalData.header
      //如果session3rd不存在则调用登录接口
      if (session3rd == "" || session3rd == null) {
        that.doLogin(function (data) {
          if (data.code == 0) {
            session3rd = data.session3rd
            wx.setStorageSync('SESSION3RD', session3rd)
            header.SESSION3RD = session3rd
            that.globalData.header = header
            that.globalData.userInfo = data.userInfo
            typeof cb == "function" && cb(that.globalData.userInfo)
          } else {
            var msg = '';
            if (data.code != null && data.code != '') msg = msg + data.code
            if (data.msg != null && data.msg != '') msg = msg + data.msg
            wx.showModal({
              title: '登陆提示',
              content: '登陆失败',
              success: function(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '../login/login',
                  })
                }
              },
              fail: function(res) {},
              complete: function(res) {},
            })
            typeof cb == "function" && cb(false)
          }
        })
      } else {
        header.SESSION3RD = session3rd
        that.globalData.header = header
        wx.request({
          url: that.globalData.requestip + '&c=User&a=getUserInfo',
          header: that.globalData.header,
          success: function (res) {
            var data = res.data
            //当code==0时表示后台能直接获取用户信息
            if (data.code == 0) {
              that.globalData.userInfo = data.userInfo
              console.log('SESSION3RD存在:登录成功')
              typeof cb == "function" && cb(that.globalData.userInfo)
            } else {
              console.log('SESSION3RD存在:登录失败')
              wx.showModal({
                title: '登陆失败',
                content: '后端程序错误',
              })
              typeof cb == "function" && cb(false)
            }
          },
          fail: function (res) {
            console.log('SESSION3RD存在:request接口调用失败，登录失败')
            wx.showModal({
              title: '登陆失败',
              content: 'SESSION3RD存在:request接口调用失败，登录失败',
            })
            typeof cb == "function" && cb(false)
          }
        })
      }
    }
  },
  //用户登录--后端判断用户是否存在，存在则查询信息，不存在则新增用户
  doLogin: function (cb) {
    var that = this
    //调用登录接口获取session_key和openid
    wx.login({
      success: function (res) {
        var code = res.code
        //获取到code
        if (res.code) {
          console.log('wx.login调用成功')
          that.checkIsFollowed(code, function (data) {
            if (data['code'] == 1003) {
              //未关注过公众号
              that.getAuthorizationInfo(data.userInfo.session_key, function (data) {
                typeof cb == "function" && cb(data)
              })
            } else {
              typeof cb == "function" && cb(data)
            }
          })
        } else {
          console.log('wx.login调用失败' + res.errMsg)
          typeof cb == "function" && cb(false)
        }
      },
      fail: function (res) {
        console.log("wx.login调用失败" + res)
        typeof cb == "function" && cb(false)
      }
    })
  },
  //检查用户是否关注过公众号，如果关注过则直接登录无需让用户确认授权，如果未关注过，则返回false,调用用户授权流程
  checkIsFollowed: function (code, cb) {
    //发起网络请求后台获取用户的session_key和openid
    var that = this
    wx.request({
      url: that.globalData.requestip + '&c=login&a=checkIsFollowed',
      data: {
        code: code
      },
      success: function (res) {
        typeof cb == "function" && cb(res.data)
      },
      fail: function (res) {
        typeof cb == "function" && cb(false)
      }
    })
  },
  //如果后台数据库不存在用户信息，则调用用户授权获取用户信息
  getAuthorizationInfo: function (session_key, cb) {
    var that = this
    wx.getUserInfo({
      withCredentials: true,
      success: function (res) {
        //发起网络请求后台获取用户的session_key和openid
        wx.request({
          url: that.globalData.requestip + '&c=login&a=doLogin',
          data: {
            session_key: session_key,
            rawData: res.rawData,
            signature: res.signature,
            encryptedData: res.encryptedData,
            iv: res.iv
          },
          success: function (res) {
            typeof cb == "function" && cb(res.data)
          },
          fail: function (res) {
            console.log("doLogin:request请求失败" + res)
            typeof cb == "function" && cb(false)
          }
        })
      },
      fail: function (res) {
        console.log('wx.getUserInfo:接口调用失败，登录失败' + res.errMsg)
        typeof cb == "function" && cb(false)
      }
    })
  },
  /**
   * 获取sessionKey
   */
  checkUserSessionKey: function (cb) {
    var that = this
    wx.checkSession({
      success: function(res) {
        typeof cb == "function" && cb(true)
      },
      fail: function(res) {
        wx.login({
          success: function (res) {
            wx.request({
              url: that.globalData.requestip + '&c=share&a=updateSessionKey',
              data: {
                code: res.code
              },
              header: that.globalData.header,
              success: function (res) {
                if (res.data.code != 0) {
                  wx.showToast({
                    title: '分享失败'
                  })
                  typeof cb == "function" && cb(false)
                } else {
                  typeof cb == "function" && cb(true)
                }
              },
              fail: function (res) { },
              complete: function (res) { },
            })
          },
          fail: function (res) {
            var res = res
          },
          complete: function (res) {
            var res = res
          },
        })
      },
      complete: function(res) {},
    })
  },
  //兼容性处理
  setBanben: function () {
    wx.getSystemInfo({
      success: function (res) {
        var b = [0, 0, 0];
        var version = res.version;
        var a = version.split(".")
        //判断版本是否验证通过
        var flage = true
        for (var p = 0; p < a.length; p++) {
          if (a[p] > b[p]) {
            break;
          }
          if (a[p] < b[p]) {
            wx.showModal({
              title: '提示',
              content: '当前微信版本过低，可能影响您的使用，请升级到最新微信版本。(目前最新版本:安卓:6.5.22,ios:6.5.23)'
            })
            flage = false
            break;
          }
        }
        //版本验证通过后，验证接口是否兼容
        if (flage) {
          if (wx.onNetworkStatusChange && wx.showLoading && wx.hideLoading && wx.getSetting && wx.getUserInfo && wx.authorize && wx.createSelectorQuery && wx.createInnerAudioContext && wx.getRecorderManager) {
            console.log("支持接口")
          } else {
            // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
            wx.showModal({
              title: '提示',
              content: '当前微信版本过低，可能影响您的使用，请升级到最新微信版本。(目前最新版本:安卓:6.5.22,ios:6.5.23)'
            })
          }
        }
        console.log(res.SDKVersion)
      }
    })
  },
  globalData: {
    userInfo: null,
    header: { 'content-type': 'application/json' },
    // ossip: 'https://hrfile.oss-cn-beijing.aliyuncs.com/',
    // requestip: 'http://localhost/czw/index.php?m=xcx',
    // uploadip: 'http://localhost/czw/index.php?m=xcx',
    // downloadip: 'https://hrfile.oss-cn-beijing.aliyuncs.com/',
    // socketip: 'wss://localhost/czw/wss:443',
    ossip: 'https://hrfile.oss-cn-beijing.aliyuncs.com/',
    requestip: 'https://www.genzf.com/index.php?m=xcx',
    uploadip: 'https://www.genzf.com/index.php?m=xcx',
    downloadip: 'https://hrfile.oss-cn-beijing.aliyuncs.com/',
    socketip: 'wss://www.genzf.com/wss:443',
  }
})